<!--
 * @Description: 选择用户
 * @Author: DHL
 * @Date: 2022-04-08 09:04:53
 * @LastEditors: dhlleo dhlleo@126.com
 * @LastEditTime: 2022-12-03 09:52:22
-->
<template>
  <tw-dialog
    v-model="visible"
    title="选择人员"
    :loading="loading"
    :showZoom="false"
    width="1100px"
    height="600px"
    heightContent="580px"
    customClass="select-user-wrapper"
    @close="handleClose"
  >
    <splitpanes class="default-theme">
      <pane :size="70" class="user-left">
        <tw-layout @refresh="handleRefresh" @search="handleSearch" @reset="handleReset">
          <!-- 查询表单 -->
          <template #header>
            <el-form ref="searchFormRef" :model="searchForm" label-width="90px">
              <el-row>
                <el-col :span="16">
                  <el-form-item label="机构">
                    <el-cascader
                      v-model="searchForm.orgId"
                      :options="orgTreeData"
                      :props="{
                        checkStrictly: true,
                        value: 'id',
                        label: 'name',
                        children: 'children'
                      }"
                      filterable
                      clearable
                      placeholder="请选择机构"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="登陆名称">
                    <el-input
                      v-model="searchForm.loginName"
                      clearable
                      placeholder="请输入登陆名称"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="姓名">
                    <el-input
                      v-model="searchForm.name"
                      clearable
                      placeholder="请输入姓名"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="用户类型">
                    <el-select v-model="searchForm.userType" clearable placeholder="请选择用户类型">
                      <tw-dic dicKey="USERTYPE"></tw-dic>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="用户状态">
                    <el-select v-model="searchForm.status" clearable placeholder="请选择用户状态">
                      <tw-dic dicKey="USER_STATUS"></tw-dic>
                    </el-select>
                  </el-form-item>
                </el-col>

                <!-- <el-col :span="6">
                  <el-form-item label="手机号码">
                    <el-input
                      v-model="searchForm.phone"
                      clearable
                      placeholder="请输入手机号码"
                    ></el-input>
                  </el-form-item>
                </el-col> -->

                <!-- <el-col :span="6">
                  <el-form-item label="职务">
                    <el-input
                      v-model="searchForm.position"
                      clearable
                      placeholder="请输入职务"
                    ></el-input>
                  </el-form-item>
                </el-col> -->
              </el-row>
            </el-form>
          </template>

          <!-- 数据表格 -->
          <tw-table
            ref="tableRef"
            :loading="loading"
            :options="tableOptions"
            :events="tableEvents"
            :data="tableData"
            @search="searchList"
          >
          </tw-table>
        </tw-layout>
      </pane>
      <pane :size="30">
        <tw-layout :btnsWidth="50">
          <!-- 按钮组 -->
          <template #btns>
            <el-button class="item" type="primary" @click="handleSubmit()">
              <svg-icon iconClass="plus"></svg-icon>
              确定人员
            </el-button>
          </template>

          <div class="selected-user-wrapper">
            <div class="user-num">已选择人员：{{ state.userList.length }}</div>
            <div class="user-list">
              <el-scrollbar height="100%">
                <draggable
                  :list="state.userList"
                  item-key="id"
                  ghost-class="ghost"
                  chosen-class="chosen"
                  animation="300"
                  @start="handleStart"
                  @end="handleEnd"
                >
                  <template #item="{ element }">
                    <div class="user-item">
                      <div class="name">{{ element.name }}</div>
                      <div class="icon" @click="handleDelete(element)">
                        <svg-icon iconClass="delete" title="删除"></svg-icon>
                      </div>
                    </div>
                  </template>
                </draggable>
              </el-scrollbar>
            </div>
          </div>
        </tw-layout>
      </pane>
    </splitpanes>
  </tw-dialog>
</template>

<script setup lang="ts" name="SelectUser">
  import { reactive, ref } from 'vue'
  import { assign, cloneDeep } from 'lodash-es'
  import { TwTableOptions } from '/@/types/table.d'
  import { UserModel, UserPageParams } from '/@/api/system/model/userModel'
  import { apiUserSearch } from '/@/api/system/user'
  import { ElMessage } from 'element-plus'
  import { arrayLastValue, arrayRemoveByPropertyValue, listToTree } from '/@/utils/twUtils'
  import { apiOrganizationSearchTree } from '/@/api/system/organization'
  import { Splitpanes, Pane } from 'splitpanes'
  import 'splitpanes/dist/splitpanes.css'
  import draggable from 'vuedraggable'

  const emit = defineEmits(['submit'])

  //////////////////////////////////////////////////
  // 属性
  //////////////////////////////////////////////////

  /**
   * 显示弹框
   */
  const visible = ref(false)

  const loading = ref(false)

  /**
   * 表格数据
   */
  const tableData = ref()

  /**
   * 查询表单
   */
  const searchFormRef = ref()

  /**
   * 数据列表
   */
  const tableRef = ref()

  const state = reactive({
    userList: [] as Array<UserModel> // 选中用户
  })

  //////////////////////////////////////////////////
  // 查询表单
  //////////////////////////////////////////////////

  const defaultSearchForm = {
    orgId: '',
    loginName: '', // 登陆名称
    name: '', // 姓名
    userType: '', // 用户类型
    phone: '', // 手机号码
    mail: '', // 邮箱
    status: '1', // 用户状态（0，失效；1，生效）
    position: '' // 职务
  }

  /**
   * 查询表单
   */
  const searchForm = reactive(cloneDeep(defaultSearchForm))

  //////////////////////////////////////////////////
  // 表格
  //////////////////////////////////////////////////

  /**
   * 表格配置
   */
  const tableOptions = reactive<TwTableOptions>({
    id: 'userListTable',
    checkboxConfig: {
      reserve: false,
      trigger: 'row'
    },
    sortConfig: {
      defaultSort: [{ field: 'loginName', order: 'asc' }]
    },
    columns: [
      // { type: 'checkbox', fixed: 'left', title: '', width: 40 },
      { type: 'seq', fixed: 'left', title: '序号', width: 50 },
      { field: 'loginName', title: '登陆名称', sortable: true, minWidth: 110 },
      { field: 'name', title: '姓名', sortable: true, minWidth: 110 },
      { field: 'orgName', title: '机构', sortable: false, minWidth: 100 },
      {
        field: 'status',
        title: '用户状态',
        sortable: true,
        width: 100,
        params: { dict: 'USER_STATUS' }
      },
      {
        field: 'userType',
        title: '用户类型',
        sortable: true,
        width: 100,
        params: { dict: 'USERTYPE' }
      }
      // { field: 'position', title: '职务', sortable: true },
      // { field: 'phone', title: '手机号码' },
      // { field: 'mail', title: '邮箱' }
    ]
  })

  /**
   * 绑定事件
   */
  const tableEvents = reactive({
    cellClick: function ({ row }) {
      const exists = state.userList.some((item) => item.id === row.id)
      if (!exists) {
        state.userList.push(row)
      }
    }
  })

  //////////////////////////////////////////////////
  // 函数
  //////////////////////////////////////////////////

  /**
   * 查询表格数据函数
   * @param queryParams
   */
  function searchList(queryParams: UserPageParams) {
    loading.value = true

    let orgId = ''
    if (searchForm.orgId && searchForm.orgId.length > 0) {
      orgId = arrayLastValue(searchForm.orgId)
    }

    apiUserSearch(
      assign(queryParams, searchForm, {
        orgId: orgId
      })
    )
      .then((result) => {
        tableData.value = result
      })
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
  }

  /**
   * 查询表格数据
   */
  function handleSearch() {
    tableRef.value.handleQuery()
  }

  /**
   * 刷新
   */
  function handleRefresh() {
    tableRef.value.handleReload()
  }

  /**
   * 重置
   */
  function handleReset() {
    assign(searchForm, cloneDeep(defaultSearchForm))
    tableRef.value.handleQuery()
  }

  /**
   * 显示弹框
   */
  function handleOpen(params: any) {
    visible.value = true

    if (params) {
      state.userList = params
    }

    handleSearchOrgTree()
  }

  /**
   * 关闭弹框
   */
  function handleClose() {
    visible.value = false
  }

  /**
   * 提交当前选中行数据
   */
  function handleSubmit() {
    if (state.userList.length < 1) {
      ElMessage.warning('请选择用户')
      return
    }

    emit('submit', state.userList)

    handleClose()
  }

  /**
   * 删除
   * @param row
   */
  function handleDelete(row: UserModel) {
    arrayRemoveByPropertyValue(state.userList, 'id', row.id)
  }

  /**
   * 拖拽开始
   */
  function handleStart() {}

  /**
   * 拖拽结束
   */
  function handleEnd() {}

  //////////////////////////////////////////////////
  // 机构
  //////////////////////////////////////////////////
  const orgTreeData = ref()

  /**
   * 查询机构数据
   */
  function handleSearchOrgTree() {
    apiOrganizationSearchTree().then((result) => {
      if (result?.success) {
        orgTreeData.value = listToTree(result?.data ? result.data : [], 'id', 'parentOrgId', '')
      }
    })
  }

  defineExpose({ handleOpen })
</script>

<style lang="scss" scoped>
  .selected-user-wrapper {
    height: 100%;
    font-size: 14px;

    .user-num {
      padding: 10px 0px;
    }

    .user-list {
      height: calc(100% - 35px);
      .user-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;
        border-radius: 3px;
        cursor: pointer;

        &:hover {
          background-color: #ebedf0;
        }

        .icon {
          color: #f56c6c;
          .svg-icon {
            width: 1.1em;
            height: 1.1em;
          }
        }

        &.chosen {
          cursor: move;
        }
      }
    }
  }
</style>
